<template>
  <div class="doctor-tell">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        v-model="searchName"
        placeholder="请输入病人编号搜索"
        class="search-input"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input> 
    </div>

    <!-- 表格区域 -->
    <el-table :data="filteredTableData" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column prop="bedCode" label="床位" width="120">
        <template #default="scope">
          {{ formatBedCode(scope.row.bedCode) }}
        </template>
      </el-table-column>
      <el-table-column prop="patientCode" label="病人" width="120" />
      <el-table-column prop="doctorContent" label="医嘱内容" />
      <el-table-column prop="doctorCode" label="医生姓名" />
      <el-table-column prop="doctorSTime" label="医嘱开始日期" width="180">
        <template #default="scope">
          {{ scope.row.doctorSTime ? new Date(scope.row.doctorSTime).toLocaleDateString() : '---' }}
        </template>
      </el-table-column>
      <el-table-column prop="doctorETime" label="医嘱结束日期" width="180" >
        <template #default="scope">
          {{ scope.row.doctorETime ? new Date(scope.row.doctorETime).toLocaleDateString() : '---' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" >
        <template #default="scope">
          <el-tag v-if="checkEffectiveStatus(scope.row)" type="success">生效中</el-tag>
          <el-tag v-else type="info">失效</el-tag>
        </template>
      </el-table-column>

    </el-table> 
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import http from '@/api/http'
import * as signalR from '@microsoft/signalr'

interface FormType {
  id?: number
  doctorCode:string
  bedCode: string
  patientCode: string
  doctorContent: string
  doctorSTime: string
  doctorETime: string
  isPublisher: 0,
  isDelete: 0
}

// 搜索相关
const searchName = ref('')
const tableData = ref<FormType[]>([]) // 添加类型定义
const filteredTableData = ref<FormType[]>([]) // 添加类型定义

// 格式化床位编码
const formatBedCode = (bedCode: string | number) => {
  if (!bedCode) return '';
  const num = parseInt(bedCode.toString());
  return `C${num < 10 ? '00' + num : num < 100 ? '0' + num : num}`;
}

// 处理搜索
const handleSearch = () => {
  if (!searchName.value) {
    // 如果搜索框为空，显示所有数据
    filteredTableData.value = tableData.value
    return
  }
  // 过滤包含搜索关键字的数据
  filteredTableData.value = tableData.value.filter(item => 
    item.patientCode?.toLowerCase().includes(searchName.value.toLowerCase())
  )
}

// 检查医嘱是否生效中
const checkEffectiveStatus = (row: FormType) => {
  const currentTime = new Date().getTime()
  const startTime = new Date(row.doctorSTime).getTime()
  
  // 如果没有开始时间，返回失效
  if (!row.doctorSTime) return false
  
  // 如果有结束时间，需要在开始和结束时间之间
  if (row.doctorETime) {
    const endTime = new Date(row.doctorETime).getTime()
    return currentTime >= startTime && currentTime <= endTime
  }
  
  // 如果没有结束时间，只需要大于开始时间
  return currentTime >= startTime
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '---';
  try {
    const date = new Date(dateStr);
    return date.toLocaleString();
  } catch (e) {
    return dateStr;
  }
}

// 获取医嘱列表
const showTell = () => {
  http.get('/api/DoctorManage/GetTellsPublisher')
    .then(res => {
      console.log('已发布医嘱列表:', res.data);
      tableData.value = res.data;
      filteredTableData.value = res.data;
      handleSearch();
    })
    .catch(err => {
      console.error('获取医嘱列表失败:', err);
      ElMessage.error('获取医嘱列表失败');
    });
}

// 监听搜索框变化
watch(searchName, () => {
  handleSearch()
})

// SignalR连接
let connection: any = null

// 初始化SignalR连接
const initConnection = async () => {
  // 如果已经有连接，不需要重新建立
  if (connection) return
  
  try {
    connection = new signalR.HubConnectionBuilder()
      .withUrl('http://localhost:9991/chatHub')
      .withAutomaticReconnect()
      .build()
    
    // 监听消息 - 收到消息时刷新列表
    // @ts-ignore  
    connection.on('MessageInfo', function(message) {
      console.log('护士端收到消息:', message)
      showTell() // 自动刷新医嘱列表
    })
    
    await connection.start()
    console.log('护士端SignalR连接已建立')
  } catch (error) {
    console.error('护士端SignalR连接失败:', error)
  }
}

// 添加页面加载时的初始化
onMounted(async () => {
  showTell() // 获取医嘱列表
  await initConnection() // 建立SignalR连接
})

// 组件卸载时关闭连接
onUnmounted(() => {
  if (connection) {
    connection.stop()
  }
})

defineProps({
    msg: String
})

</script>

<style scoped>
.doctor-tell {
  padding: 20px;
}

.search-area {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}
</style>